package cn.micai.base.io;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * 描述：如何将文件转换为字节
 * <p>
 *
 * @author: 赵新国
 * @date: 2018/6/20 15:36
 */
public class FileToArrayOfBytes {

    public static void main(String [] args) {

        try {
            // convert file to byte[]
//            byte [] bFile = readBytesFromFile("D://newFile.txt");


            //java nio
//            byte[] bFile = Files.readAllBytes(new File("D://newFile.txt").toPath());
            byte[] bFile = Files.readAllBytes(Paths.get("D://newFile.txt"));


            // save byte[] into a file
            Path path = Paths.get("D://test2.txt");
            Files.write(path, bFile);

            System.out.println("Done");

            //Print bytes[]
            /*for (int i = 0; i < bFile.length; i++) {
                System.out.print((char) bFile[i]);
            }*/
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private static byte[] readBytesFromFile(String filePath) {
        FileInputStream fileInputStream = null;
        byte[] bytesArray = null;

        try {
            File file = new File(filePath);
            bytesArray = new byte[(int) file.length()];

            // read file into bytes[]
            fileInputStream = new FileInputStream(file);
            fileInputStream.read(bytesArray);

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return bytesArray;
    }
}
